//
//  TGDefaultsLoader.m
//  ThinkGeek LED Clock
//
//  Created by Tim Morgan on 4/29/05.
//  Copyright 2005 __MyCompanyName__. All rights reserved.
//

#import "TGDefaultsLoader.h"

TGDefaultsLoader *defaultsLoaderSingleton;

@implementation TGDefaultsLoader

#pragma mark <<initialization/singleton>>

- (void) awakeFromNib {
	defaultsLoaderSingleton = self;
	defaults = [ScreenSaverDefaults defaultsForModuleWithName:@"org.tmorgan.ThinkGeekLEDClock"];
}

+ (TGDefaultsLoader *) loader {
	if (defaultsLoaderSingleton == nil)
		[[NSException exceptionWithName:@"TGUnexpectedInvocationException"
								 reason:@"Tried to access the TGDefaultsLoader singleton before it had been created."
							   userInfo:nil] raise];
	return defaultsLoaderSingleton;
}

#pragma mark -
#pragma mark <<defaults>>

- (void) loadDefaults {
	NSString *versionString = [defaults stringForKey:@"version"];
	if (![versionString isEqualToString:[TGStringConstants version]] || versionString == nil) {
		// this is our first time running the screensaver; we need to make a config
		[self createNewDefaults];
	}
	
	NSEnumerator *keyEnum = [[[TGDefaultsModel defaultsModel] keys] objectEnumerator];
	id currentKey;
	while (currentKey = [keyEnum nextObject]) {
		[defaultsModel setValue:[self unloadKey:currentKey] forKey:currentKey];
	}
}

- (void) writeDefaults {
	NSEnumerator *keyEnum = [[[TGDefaultsModel defaultsModel] keys] objectEnumerator];
	id currentKey;
	while (currentKey = [keyEnum nextObject]) {
		[self loadObject:[defaultsModel valueForKey:currentKey] forKey:currentKey];
	}
	
	[defaults synchronize];
}

- (void) createNewDefaults {
	NSEnumerator *keyEnum = [[[TGDefaultsModel defaultsModel] keys] objectEnumerator];
	id currentKey;
	while (currentKey = [keyEnum nextObject]) {
		[self loadObject:[defaultsModel standardDefaultForKey:currentKey] forKey:currentKey];
	}
	
	[defaults synchronize];
}

#pragma mark -
#pragma mark <<types>>

- (id) unloadKey:(NSString *)key {
	id object = [defaults objectForKey:key];
	if ([object isKindOfClass:[NSData class]]) return [self unarchiveColorFromDefaults:object];
	else return object;
}

- (void) loadObject:(id)object forKey:(NSString *)key {
	if ([object isKindOfClass:[NSData class]]) [defaults setObject:[self archiveColorForDefaults:object] forKey:key];
	else [defaults setObject:object forKey:key];
}

- (NSData *) archiveColorForDefaults:(NSColor *)color {
	if (color == nil) color = [NSColor blackColor];
	NSData *archivedColor = [NSArchiver archivedDataWithRootObject:color];
	return archivedColor;
}

- (NSColor *) unarchiveColorFromDefaults:(NSData *)archive {
	if (archive == nil) return nil;
	NSColor *color = (NSColor *) [NSUnarchiver unarchiveObjectWithData:archive];
    if (color == nil) return [NSColor blackColor];
	else return color;
}

@end
